package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"github.com/labstack/gommon/log"
	"quiz/models"
	"strconv"
)

type LoginController struct {
	CommonController
}

type loginForm struct {
	code          string
	encryptedData string
	iv            string
}

// URLMapping ...
func (c *LoginController) URLMapping() {
	c.Mapping("Login", c.Post)

}

// Login ...
// @Title Login
// @Description 获取登陆信息
// @Param	code		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Resp
// @Failure 403 :code is empty
// @router /:code [get]
func (c *LoginController) Login() {
	var form loginForm
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &form); err != nil {
		log.Info("登陆发生异常", err)
		c.SendResponse(models.CheckError(err))
	}

	loginResp, err := models.CodeToSession(form.code)
	//保存SessionKey
	token := models.SaveSessionKeyToCache(loginResp.Sessionkey, loginResp.Openid)
	//获取头像昵称
	result, err := models.AesDecrypt(form.encryptedData, loginResp.Sessionkey, form.iv)
	if err != nil {
		c.SendResponse(models.CheckError(err))
	}
	var data = make(map[string]interface{})
	data = result.(map[string]interface{})
	//保存用户信息
	nickname := data["nickname"].(string)
	headimgurl := data["headimgurl"].(string)
	//判断是否存在该用户
	userInfo, err := models.GetUserInfoByOpenId(loginResp.Openid)
	if err != nil {
		if err == orm.ErrNoRows {
			//不存在则新增
			id, err := models.AddUserInfo(&models.UserInfo{Id: nil, Username: nickname, HeadImg: headimgurl, Unionid: nil, Openid: loginResp.Openid, CreTime: nil, State: nil})
			if err != nil {
				c.SendResponse(models.CheckError(err))
			}
			log.Info("新增用户,id为" + strconv.FormatInt(id, 10))
		} else {
			c.SendResponse(models.Success(token))
		}
	} else {
		newUserInfo := models.UserInfo{Id: userInfo.Id, Username: nickname, HeadImg: headimgurl, Unionid: nil, Openid: loginResp.Openid, CreTime: nil, State: nil}
		if err := models.UpdateUserInfoById(&newUserInfo); err != nil {
			c.SendResponse(models.CheckError(err))
		}
	}

	c.SendResponse(models.Success(token))

}
